<template>
  <div class="demo-02">
    <div>{{ startTime }} 至 {{ endTime }}</div>

    <el-date-picker
      v-model="startTime"
      type="date"
      value-format="yyyy-MM-dd HH:mm:ss"
      placeholder="选择开始日期"
      :picker-options="startPickerOptions"
      @change="handleStartTimeChange"
    >
    </el-date-picker>
    至
    <el-date-picker
      v-model="endTime"
      type="date"
      value-format="yyyy-MM-dd HH:mm:ss"
      placeholder="选择结束日期"
      :picker-options="endPickerOptions"
      @change="handleEndTimeChange"
    >
    </el-date-picker>
  </div>
</template>

<script>
export default {
  data() {
    return {
      startTime: '',
      endTime: ''
    }
  },
  computed: {
    startPickerOptions() {
      return {
        disabledDate: (time) => {
          if (this.endTime) {
            return time.getTime() > new Date(this.endTime).getTime()
          }
          return false
        }
      }
    },
    endPickerOptions() {
      return {
        disabledDate: (time) => {
          if (this.startTime) {
            return time.getTime() < new Date(this.startTime).getTime()
          }
          return false
        }
      }
    }
  },
  methods: {
    handleStartTimeChange(val) {
      if (val) {
        this.startTime = `${val.split(' ')[0]} 00:00:00`
        if (this.endTime && new Date(this.startTime) > new Date(this.endTime)) {
          this.endTime = ''
        }
      }
    },
    handleEndTimeChange(val) {
      if (val) {
        this.endTime = `${val.split(' ')[0]} 23:59:59`
        if (this.startTime && new Date(this.startTime) > new Date(this.endTime)) {
          this.startTime = ''
        }
      }
    }
  }
}
</script>
